<!-- 添加/修改 英雄 -->
<template>
  <div class="hero_edit">
    <!-- 标题 -->
    <div style="overflow: hidden;">
      <h2 class="title"> {{ isId ? '编辑' : '添加'}}英雄： </h2>
    </div>
    <el-form :model="form">
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="基础属性" name="first">
          <!-- 头像列 -->
          <el-row>
            <el-col :span="10">
              <el-form-item label="展示" class="img">
                <upload @uploadUrl="uploadUrl" index='1' :icon="heroImg" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="2">
              <el-form-item label="头像" class="icon">
                 <upload @uploadUrl="uploadUrl" index='2' :icon="heroIcon" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 姓名 和 称号列 -->
          <el-row>
            <el-col v-for="(item, i) in nameAndTitle" :key="item.label+i" :span="6" :offset="item.offset">
              <el-form-item :label="item.label">
                <el-input v-model="form[item.value]"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 职位列 -->
          <el-row>
            <el-col :span="6">
              <el-form-item label="职位">
                <el-select v-model="form.position" multiple placeholder="请选择英雄的职业">
                  <el-option
                    v-for="item in positions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 打星列 -->
          <el-row v-for="row in star" :key="row[0]">
            <el-col v-for="item in row" :key="item.label" :span="6" :offset="item.offset">
              <el-form-item :label="item.label">
                <el-rate v-model="form.cover[item.value]"></el-rate>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 装备列 -->
          <el-row>
            <el-col :span="6">
              <el-form-item label="顺风出装">
                 <el-select
                    v-model="form.equip1"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="查找"
                    :remote-method="remoteMethod"
                    :loading="loading">
                    <el-option
                      v-for="item in options1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" :offset="6">
              <el-form-item label="逆风出装">
                 <el-select
                    v-model="form.equip2"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    placeholder="查找"
                    :remote-method="remoteMethod"
                    :loading="loading">
                    <el-option
                      v-for="item in options2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 技巧列 -->
          <el-row v-for="item in textareas" :key="item.label">
            <el-col :span="20">
              <el-form-item :label="item.label">
                <el-input  type="textarea" :rows="4" v-model="form[item.value]"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="技能属性" name="second">
          <el-row>
            <el-col :span="1">
              <el-button type="primary" @click="addSkill">添加技能</el-button>
            </el-col>
          </el-row>
          <div class="skills">
            <div class="skill_item" v-for="(item, index) in form.skill" :key="item">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="图标">
                    <upload @uploadUrl="uploadUrlSkill" :index="index" :icon="skillIcon[index]" />
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-row>
                    <el-col>
                      <el-form-item label="名称">
                        <el-input v-model="form.skill[index]['sname']"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col>
                      <el-form-item label="消耗">
                        <el-input v-model="form.skill[index]['sconsume']"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col>
                      <el-form-item label="冷却">
                        <el-input v-model="form.skill[index]['scooling']"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item label="描述">
                    <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="form.skill[index]['scontent']">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="3" :offset="17">
                  <el-button type="danger" @click="form.skill.splice(index, 1)">删除</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane 
          :label="tabs.label" 
          :name="tabs.name" 
          class="collocation"
          v-for="tabs in heroRelationship"
          :key="tabs.label">
          <!-- 标题 -->
          <div style="overflow: hidden; margin-bottom: 10px">
            <h4 class="title">{{tabs.label}}:</h4>
            <el-button type="primary" size="small" @click="form[tabs.text].push({hero: '', description: '' })">添加英雄</el-button>
          </div>
          <!-- 查找框 -->
          <div class="parteners">
            <div class="partners_item" v-for="(item, i) in form[tabs.text]" :key="item.hero">
              <!-- 选择英雄 -->
              <el-row>
                <el-col :span="5">
                  <el-form-item label="英雄">
                    <el-select v-model="form[tabs.text][i]['hero']" filterable placeholder="请选择">
                      <el-option
                        v-for="list in hero"
                        :key="list.value + new Date()"
                        :label="list.label"
                        :value="list.value">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 描述 -->
              <el-row>
                <el-col :span="15">
                  <el-form-item label="操作">
                    <el-input type="textarea" v-model="form[tabs.text][i]['description']" placeholder="和英雄如何搭配" :rows="5"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="2" :offset="13">
                  <el-button type="danger" @click="form[tabs.text].splice(i, 1)">删除</el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-form-item class="btn">
        <el-row>
          <el-col :span="4">
            <el-button type="success" @click="onSubmit">确定</el-button>
            <el-button @click="router.push('/heros/list')">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts'>
import { computed, defineComponent, onMounted, reactive, toRefs } from 'vue';
import Upload from '../../components/Upload.vue';
import axios from '../../http/axios';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

interface center {
  activeName: string;
  form: {
    name: string;
    title: string;
    img: string;
    icon: string;
    position: string[];
    cover: {
      difficulty: number;
      cskill: number;
      attack: number;
      existence: number;
    },
    equip1: any[];
    equip2: any[];
    skill: any[];
    usageTips: string;
    battleTips: string;
    teamTips: string;
    parteners: any[];
    beRestrained: any[];
    restrainWho: any[];
  };
  loading: boolean;
  nameAndTitle: any[];
  star: any[];
  equip: any[];
  hero: any[];
  heroRelationship: any[];
  router: any;
  skillIcon: any[];
  options1: any[];
  options2: any[];
  heroImg: string;
  heroIcon: string;
}

export default defineComponent ({
  name: 'EquipList',
  components: { Upload },
  props: ['id'],
  setup (props) {
    const content: center = reactive({
      router: useRouter(),

      activeName: 'first',

      form: {
        name: '',
        title: '',
        img: '',
        icon: '',
        position: [],     // 职位
        cover: {
          difficulty: 0,  // 难度
          cskill: 0,      // 技能
          attack: 0,      // 攻击
          existence: 0,   // 生存
        },
        equip1: [],       // 顺风出装
        equip2: [],       // 逆风出装
        skill: [{ sname: '', scontent: '', sicon: '', sconsume: '', scooling: '' }],
        usageTips: '',    // 使用技巧
        battleTips: '',   // 对抗技巧
        teamTips: '',     // 团战思路
        parteners: [      // 搭档英雄，存储英雄id 和 描述
          { hero: '', description: '' }
        ],
        beRestrained: [      // 被谁克制
          { hero: '', description: '' }
        ],
        restrainWho: [      // 克制英雄
          { hero: '', description: '' }
        ], 
      },

      // 存储英雄列表数据
      hero: [],

      // select 组件
      loading: false,
      // 接收装备数据
      options1: [],
      options2: [],

      // 存储技能的图标
      skillIcon: [],
      // 存储英雄展示图
      heroImg: '',
      // 存储英雄头像
      heroIcon: '',

      // 监听 id 的变化
      isId: computed(() => {
        return props.id ? true : false;
      }),

      nameAndTitle: [
        { label: '姓名', value: 'name', offset: 0 },
        { label: '称号', value: 'title', offset: 6 },
      ],

      star: [
        [
          { label: '难度', value: 'difficulty', offset: 0 },
          { label: '技能', value: 'cskill', offset: 6 },
        ],
        [
          { label: '攻击', value: 'attack', offset: 0 },
          { label: '生存', value: 'existence', offset: 6 },
        ]
      ],

      equip: [
        { label: '顺风出装',  value: 'equip1', offset: 0 },
        { label: '逆风出装',  value: 'equip2', offset: 6 }
      ],

      textareas: [
        { label: '使用技巧',  value: 'usageTips' },
        { label: '对抗技巧',  value: 'battleTips' },
        { label: '团战思路',  value: 'teamTips' },
      ],

      heroRelationship: [
        { label: '搭档英雄', text: 'parteners', name: 'third' },
        { label: '被谁克制', text: 'beRestrained', name: 'fourth' },
        { label: '克制英雄', text: 'restrainWho', name: 'fifth' },
      ],

      positions: [
        { value: '战士' },
        { value: '法师' },
        { value: '刺客' },
        { value: '辅助' },
        { value: '坦克' },
        { value: '射手' },
      ]
    });

    // 页面存在 id 时，发送获取数据的请求
    props.id && selectById();

    // 在初始化时，获取英雄列表
    async function getHero() {
      const { data } = await axios.get('heros/page');
      // 循环获取到的英雄数据，并 push 到 hero 中
      data.content.forEach((item: any) => {
        content.hero.push({ label: item.name, value: item._id })
      })
    }

    // 上传组件 传递的参数
    function uploadUrl ([url, index]: [string, string]) {
      if (index == '1') {
        content.form.img = url;
      } else {
        content.form.icon = url;
      }
    }

    // 技能的上传组件,上传时，把当前项的索引传递到 上传组件，再返回来，
    // 就可以知道是哪个技能的上传组件了。
    function uploadUrlSkill([url, index]: [string, number]) {
      content.form.skill[index]['sicon'] = url;
    }

    // select 组件，输入触发
    async function remoteMethod(query: any) {
      // query 输入文本框时的数据
      if (query !== '') {
          // 正在 请求
          content.loading = true;
          const { data }: { data: any } = await axios.get(`equips/name/${query}`);
          content.options1.push({label: data.name, value: data._id});
          content.loading = false;
      } else {
        content.options1 = [];
      }
    }

    // 点击添加技能按钮，添加新一项技能
    function addSkill() {
      content.form.skill.push({ sname: '', scontent: '', sicon: '', sconsume: '', scooling: '' })
    }

    // 点击提交表单
    async function onSubmit() {
      props.id ? upt() : create();
    }

    // 创建英雄
    async function create() {
      const { data } = await axios.post('heros', content.form);
      ElMessage.success(data.success);
      content.router.push('/heros/list');
    }

    // 修改英雄
    async function upt() {
      const { data } = await axios.put(`heros/${props.id}`, content.form);
      console.log(content.form);
      console.log(data);
      ElMessage.success(data.success);
      content.router.push('/heros/list');
    }

    // 编辑时，获取英雄数据
    async function selectById() {
      
      const { data } = await axios.get(`/heros/${props.id}`);
      console.log(data);
      // 拷贝一份数据
      let newObj: any = {};
      Object.assign(newObj, data);

      // 设置装备 在 input 中的显示
      content.options1 = data.equip1.map((item: any) => {
        return { value: item._id, label: item.name }
      })
      content.options2 = data.equip2.map((item: any) => {
        return { value: item._id, label: item.name }
      })

      // 获取英雄展示图 和 头像
      content.heroImg = data.img;
      content.heroIcon = data.icon;

      content.skillIcon = data.skill.map((item: any) => {
        return item.sicon;
      })
      console.log(newObj);

      content.form = newObj;
    }

    onMounted(() => {
      getHero()
    })

    const refContent = toRefs(content);

      return {
        ...refContent,
        uploadUrl,
        remoteMethod,
        addSkill,
        onSubmit,
        uploadUrlSkill,
    }
  }
})

</script>

<style lang='scss' scoped>
.hero_edit {
  // 标题
  .title {
    margin-bottom: 20px;
  }
  // 提交按钮
  .btn {
    margin-top: 50px;
  }
  // 技能
  .skills {
    display: flex;
    flex-wrap: wrap;
    .skill_item {
      width: 50%;
      margin-top: 40px;
    }
  }
  // 英雄搭配
  .collocation {
    h4 {
      font-weight: 400;
      display: inline-block;
      margin-right: 10px;
    }
    .el-button {
      float: left;
    }
  }
}
</style>